    //引入jQuery
	import $ from 'jquery'; 
	
	
	//卡尔读卡器对接对象
    let CAERcardService ={
        param:{
            index_list:[],
            timer:[],
            baseUrl : "http://127.0.0.1:6045",
            wzObj:null,
            timer_time:2000,
            error_info:'',
            timeout:100000, //检测超时时间
            callback:[],//function (service,wzObj,error_info){},
            successcall:[],//function (service,wzObj){},
            errorcall:[] //function (service,error_info){}
        },
        setCallback:function (callback){
            this.param.callback.push(callback);
        },
        setError:function (callback){
            this.param.errorcall.push(callback);
        },
        setSuccess:function (callback){
            this.param.successcall.push(callback);
        },
        clearCallback:function (){
            this.param.callback = [];
        },
        clearError:function (){
            this.param.errorcall= [];
        },
        clearSuccess:function (){
            this.param.successcall= [];
        },
        clearAllCallback:function (){
            this.clearCallback();
            this.clearError();
            this.clearSuccess();
        },
        runCallback:function (service,wzObj,error_info){
            this.param.callback.forEach(function(item,index,self){
                // item 遍历出的每一个元素
                //
                // index 元素对应的下标
                //
                // self 数组本身
                //
                // 无返回值
                item(service,wzObj,error_info);
            })

        },
        runErrorCallback:function (service,wzObj){
            this.param.errorcall.forEach(function(item,index,self){
                // item 遍历出的每一个元素
                //
                // index 元素对应的下标
                //
                // self 数组本身
                //
                // 无返回值
                item(service,wzObj);
            })
        },
        runSuccessCallback:function (service,error_info){
            this.param.successcall.forEach(function(item,index,self){
                // item 遍历出的每一个元素
                //
                // index 元素对应的下标
                //
                // self 数组本身
                //
                // 无返回值
                item(service,error_info);
            })
        },


        setTimer:function (millisecond){
            this.param.timer_time = millisecond;
        },
        setTimeout:function (millisecond){
            this.param.timeout = millisecond;
        },
        getCarInfo:function (){
            return this.param.wzObj;
        },
        getCarNumber:function (){
            if(!this.param.wzObj)return "";
            return this.param.wzObj.gmsfhm;
        },
        getCarImage:function (){
            return this.param.wzObj;
        },
        getCarName:function (){
            if(!this.param.wzObj)return "";
            return this.param.wzObj.xm;
        },
        getErrorInfo:function (){
            return this.param.wzObj.error_info;
        },
        copyToClip:function (content,tips) {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(content).then(
                    // 复制成功callback
                    function(){
                        if(tips == null){
                            // alert("复制成功");
                        }else{
                            // alert(tips);
                        }
                        Toastr.info("身份证号已复制进剪切板，使用Ctrl+ V可粘贴使用！");
                    },
                    // 复制失败callback
                    function(){
                        // alert("复制失败");
                        // Toastr.error("复制失败，请重试！");
                    },
                )
            }
        },
        run: function (){
            let self = this;

            // //设置读取周期
            // this.setTimer(1000);
            // //设置设备读取超时时间
            // this.setTimeout(10000);

            $.ajax({
                contentType:"application/json;charset=UTF-8",
                dataType: 'jsonp',
                timeout:self.param.timeout,
                jsonp:"callback",
                url: self.param.baseUrl + "/getCardReaderList",
                success: function(resultInfo, status) {
                    let strArray = resultInfo;
                    self.stop();
                    for(let i = 0; i < resultInfo.length; i++){
                        self.param.index_list[i] = strArray[i].index;
                    }
                    //进行循环读卡监听
                    self.listen();
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    self.param.error_info = "getReader error status "+ textStatus+" errorThrown "  +errorThrown + "\r\n 未检测到读卡服务，请确认读卡服务是否在运行，是否被杀毒软件优化关闭！";
                    //触发error回调
                    self.runErrorCallback(self,self.param.error_info);
                    //触发回调
                    self.runCallback(self,self.param.wzObj,self.param.error_info);
                    // console.error("getReader error status "+ textStatus+" errorThrown "  +errorThrown + "\r\n 未检测到读卡服务，请确认读卡服务是否在运行，是否被杀毒软件优化关闭！")
                }
            });
        },
        listen:function () {
            for(let i = 0; i < this.param.index_list.length; i++){
                this.check(this.param.index_list[i]);//先主动调一次
                //定时轮询
                this.param.timer[i] = setInterval(() => {
                    this.check(this.param.index_list[i]);
                },this.param.timer_time);
            }
        },
        stop:function (){
            if(this.param.index_list.length){
                for(let i = 0; i < this.param.index_list.length; i++){
                    clearInterval(this.param.index_list.pop());
                }

            }
        },
        check: function (readerIndex){
            let self = this;
            let param = '{"portType": 5}';
            // console.info("read card", readerIndex, param)
            $.ajax({
                contentType:"application/json;charset=UTF-8",
                dataType: 'jsonp',
                timeout:self.param.timeout,
                jsonp:"callback",
                url: this.param.baseUrl + "/readIDCard?param=" + param + "&index="+readerIndex,
                success: function(resultInfo, status) {
                    // console.info("readIDCard ", resultInfo, status);
                    if( resultInfo.result === 0 ){
                        let textInfo = resultInfo.wzInfo;
                        self.param.wzObj = self.parseCardWzxx(textInfo);
                        //触发成功回调
                        self.runSuccessCallback(self,self.param.wzObj);
                        // console.info("read card success", self.param.wzObj) ;

                        // $.ajax({
                        //     contentType:"application/json;charset=UTF-8",
                        //     dataType: 'jsonp',
                        //     jsonp:"callback",
                        //     url:baseUrl +"/wltUnpack?wlt="+resultInfo.zpWlt+"&format=JPG",
                        //     success:function(response){
                        //         if(response['result'] === 0){
                        //             var imageBase64 = response['image'];
                        //             $("#text_photobase64").val(imageBase64);
                        //             document.all['PhotoDisplay'].src = 'data:image/jpeg;base64,' + imageBase64;
                        //         }else{
                        //             alert("unpack error " + response['result']);
                        //         }
                        //     },
                        //     complete: function(XMLHttpRequest, textStatus) {
                        //     }
                        // });
                    }else{
                        // console.error("读卡失败！未读取到任何信息！");
                        self.param.error_info ="读卡失败！未读取到任何信息！";
                        //触发error回调
                        self.runErrorCallback(self,self.param.error_info);
                    }
                    //触发回调
                    self.runCallback(self,self.param.wzObj,self.param.error_info);

                },
                complete: function(XMLHttpRequest, textStatus) {
//            alert("cloudReadCard/appId complete");
//                 console.info("complete");
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    self.param.error_info = "read card request error  ", textStatus, errorThrown ;
                    // console.error("read card request error  ", textStatus, errorThrown );
                    //触发error回调
                    self.runErrorCallback(self,self.param.error_info);
                    //触发回调
                    self.runCallback(self,self.param.wzObj,self.param.error_info);
                }
            });
        },

        parseCardWzxx:function(wzxx){
            let result = {};

            result['xm'] = wzxx.substr(0, 15);
            result['xbdm'] = wzxx.substr(15, 1);
            result['mzdm'] = wzxx.substr(16, 2);
            result['csrq'] = wzxx.substr(18, 8);
            result['dzmc'] = wzxx.substr(26, 35);
            result['gmsfhm'] = wzxx.substr(61, 18);
            result['qfjgmc'] = wzxx.substr(79, 15);
            result['qfjgmc'] = wzxx.substr(79, 15);
            result['yxqqsrq'] = wzxx.substr(94, 8);
            result['yxqjzrq'] = wzxx.substr(102, 8);
            result['zjlxbs'] = wzxx.substr(124, 1);

            switch (result['xbdm']) {
                case '1': result['xbmc'] = '男'; break;
                case '2': result['xbmc'] = '女'; break;
                default: result['xbmc'] = '未知';
            }

            if (result['zjlxbs'] == 'J'){
                result['txzhm'] = wzxx.substr(110, 9);
                result['qfcs'] = wzxx.substr(119, 2);
            }

            switch (result['mzdm']) {
                case '01': result['mzmc'] = '汉'; break;
                case '02': result['mzmc'] = '蒙古'; break;
                case '03': result['mzmc'] = '回'; break;
                case '04': result['mzmc'] = '藏'; break;
                case '05': result['mzmc'] = '维吾尔'; break;
                case '06': result['mzmc'] = '苗'; break;
                case '07': result['mzmc'] = '彝'; break;
                case '08': result['mzmc'] = '壮'; break;
                case '09': result['mzmc'] = '布依'; break;
                case '10': result['mzmc'] = '朝鲜'; break;
                case '11': result['mzmc'] = '满'; break;
                case '12': result['mzmc'] = '侗'; break;
                case '13': result['mzmc'] = '瑶'; break;
                case '14': result['mzmc'] = '白'; break;
                case '15': result['mzmc'] = '土家'; break;
                case '16': result['mzmc'] = '哈尼'; break;
                case '17': result['mzmc'] = '哈萨克'; break;
                case '18': result['mzmc'] = '傣'; break;
                case '19': result['mzmc'] = '黎'; break;
                case '20': result['mzmc'] = '傈僳'; break;
                case '21': result['mzmc'] = '佤'; break;
                case '22': result['mzmc'] = '畲'; break;
                case '23': result['mzmc'] = '高山'; break;
                case '24': result['mzmc'] = '拉祜'; break;
                case '25': result['mzmc'] = '水'; break;
                case '26': result['mzmc'] = '东乡'; break;
                case '27': result['mzmc'] = '纳西'; break;
                case '28': result['mzmc'] = '景颇'; break;
                case '29': result['mzmc'] = '柯尔克孜'; break;
                case '30': result['mzmc'] = '土'; break;
                case '31': result['mzmc'] = '达翰尔'; break;
                case '32': result['mzmc'] = '仫佬'; break;
                case '33': result['mzmc'] = '羌'; break;
                case '34': result['mzmc'] = '布朗'; break;
                case '35': result['mzmc'] = '撒拉'; break;
                case '36': result['mzmc'] = '毛南'; break;
                case '37': result['mzmc'] = '仡佬'; break;
                case '38': result['mzmc'] = '锡伯'; break;
                case '39': result['mzmc'] = '阿昌'; break;
                case '40': result['mzmc'] = '普米'; break;
                case '41': result['mzmc'] = '塔吉克'; break;
                case '42': result['mzmc'] = '怒'; break;
                case '43': result['mzmc'] = '乌孜别克'; break;
                case '44': result['mzmc'] = '俄罗斯'; break;
                case '45': result['mzmc'] = '鄂温克'; break;
                case '46': result['mzmc'] = '德昂'; break;
                case '47': result['mzmc'] = '保安'; break;
                case '48': result['mzmc'] = '裕固'; break;
                case '49': result['mzmc'] = '京'; break;
                case '50': result['mzmc'] = '塔塔尔'; break;
                case '51': result['mzmc'] = '独龙'; break;
                case '52': result['mzmc'] = '鄂伦春'; break;
                case '53': result['mzmc'] = '赫哲'; break;
                case '54': result['mzmc'] = '门巴'; break;
                case '55': result['mzmc'] = '珞巴'; break;
                case '56': result['mzmc'] = '基诺'; break;
                case '59': result['mzmc'] = '穿青人'; break;
                case '60': result['mzmc'] = '革家人'; break;
                case '97': result['mzmc'] = '其它'; break;
                case '98': result['mzmc'] = '入籍'; break;
                case '99': result['mzmc'] = '其它'; break;
                default: result['mzmc'] = '';
            }
            return result;
        }


    }

    //精伦读卡器对接对象
    let jinglunCardService ={
        param:{
            webSocketUrl : "ws://127.0.0.1:18890",
            wzObj:null,
            error_info:'',
            ACardResult:null,
            websocket:null,
            callback:[],//function (service,wzObj,error_info){},
            successcall:[],//function (service,wzObj){},
            errorcall:[] //function (service,error_info){}
        },
        setCallback:function (callback){
            this.param.callback.push(callback);
        },
        setError:function (callback){
            this.param.errorcall.push(callback);
        },
        setSuccess:function (callback){
            this.param.successcall.push(callback);
        },

        clearCallback:function (){
            this.param.callback = [];
        },
        clearError:function (){
            this.param.errorcall= [];
        },
        clearSuccess:function (){
            this.param.successcall= [];
        },
        clearAllCallback:function (){
            this.clearCallback();
            this.clearError();
            this.clearSuccess();
        },
        runCallback:function (service,wzObj,error_info){
            this.param.callback.forEach(function(item,index,self){
                // item 遍历出的每一个元素
                //
                // index 元素对应的下标
                //
                // self 数组本身
                //
                // 无返回值
                item(service,wzObj,error_info);
            })

        },
        runErrorCallback:function (service,wzObj){
            this.param.errorcall.forEach(function(item,index,self){
                // item 遍历出的每一个元素
                //
                // index 元素对应的下标
                //
                // self 数组本身
                //
                // 无返回值
                item(service,wzObj);
            })
        },
        runSuccessCallback:function (service,error_info){
            this.param.successcall.forEach(function(item,index,self){
                // item 遍历出的每一个元素
                //
                // index 元素对应的下标
                //
                // self 数组本身
                //
                // 无返回值
                item(service,error_info);
            })
        },

        getCarInfo:function (){
            return this.param.wzObj;
        },
        getCarNumber:function (){
            if(!this.param.wzObj)return "";
            return this.param.wzObj.resultContent.certNumber;
        },
        getCarName:function (){
            if(!this.param.wzObj)return "";
            return this.param.wzObj.resultContent.partyName;
        },
        getCarImage:function (){
             let head_image = this.param.wzObj.resultContent.identityPic;
            head_image = "data:image/jpeg;base64," + head_image;
            // if (this.param.wzObj.name == "readCert" || this.param.wzObj.name == "PushWithImg")
            // {
            //     // document.getElementById("PhotoDisplay").src = "data:image/jpeg;base64," + resultObj.resultContent.identityPrintPic;
            //     // document.getElementById("FrontPic").src = "data:image/jpeg;base64," + resultObj.resultContent.identityFrontPic;
            //     // document.getElementById("BackPic").src = "data:image/jpeg;base64," + resultObj.resultContent.identityBackPic;
            // }
            return head_image;
        },
        getErrorInfo:function (){
            return this.param.error_info;
        },
        copyToClip:function (content,tips) {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(content).then(
                    // 复制成功callback
                    function(){
                        if(tips == null){
                            // alert("复制成功");
                        }else{
                            // alert(tips);
                        }
                        Toastr.info("身份证号已复制进剪切板，使用Ctrl+ V可粘贴使用！");
                    },
                    // 复制失败callback
                    function(){
                        // alert("复制失败");
                        // Toastr.error("复制失败，请重试！");
                    },
                )
            }
        },
        openWebSocket :function(callback){
            //不重复加载
        if(this.param.websocket)return this.param.websocket;

        let url = this.param.webSocketUrl;
        if('WebSocket' in window) {
            //websocket = new WebSocket(url,[token]);
            this.param.websocket = new WebSocket(url);
        } else if('MozWebSocket' in window) {
            console.log("MozWebSocket");
            this.param.websocket = new MozWebSocket(url);
        } else {
            console.log("SockJS");
            //websocket = new SockJS("localhost:8088/websocket/webSocketByTomcat/"+document.getElementById('sessionId').value);
        }

        if(this.param.websocket == null)
        {
            Toastr.error("创建精伦读卡器WebSocket对象失败");
        }

        //连接发生错误的回调方法
            this.param.websocket.onerror = function () {
            Toastr.error("精伦读卡器WebSocket连接发生错误");
        };
         let that = this;
        //连接成功建立的回调方法
            this.param.websocket.onopen = function () {
                console.log("WebSocket连接成功");
                if(callback)callback(that);
        };
        //接收到消息的回调方法
            this.param.websocket.onmessage = function (event) {
                console.log(event.data);

                that.param.wzObj = eval('(' +event.data+')');

                let resultObj = that.param.wzObj;
            //resultFlag为0代表读卡成功
            if (resultObj.name == "readCard" || resultObj.name == "readCert"
                || resultObj.name == "PushWithImg" || resultObj.name == "PushWithOutImg")
            {
                if (resultObj.resultFlag == "0") {
                    // //回显相关数据
                    // document.getElementById("signature").value = resultObj.signature;
                    // document.getElementById("venderId").value = resultObj.venderId;
                    // document.getElementById("certType").value = resultObj.resultContent.certType;
                    // document.getElementById("partyName").value = resultObj.resultContent.partyName;
                    // document.getElementById("gender").value = resultObj.resultContent.gender;
                    // document.getElementById("nation").value = resultObj.resultContent.nation;
                    // document.getElementById("bornDay").value = resultObj.resultContent.bornDay;
                    // document.getElementById("certAddress").value = resultObj.resultContent.certAddress;
                    // document.getElementById("certNumber").value = resultObj.resultContent.certNumber;
                    // document.getElementById("certOrg").value = resultObj.resultContent.certOrg;
                    // document.getElementById("effDate").value = resultObj.resultContent.effDate;
                    // document.getElementById("expDate").value = resultObj.resultContent.expDate;
                    // document.getElementById("HeadPic").src = "data:image/jpeg;base64," + resultObj.resultContent.identityPic;
                    // if (resultObj.name == "readCert" || resultObj.name == "PushWithImg")
                    // {
                    //     document.getElementById("PhotoDisplay").src = "data:image/jpeg;base64," + resultObj.resultContent.identityPrintPic;
                    //     document.getElementById("FrontPic").src = "data:image/jpeg;base64," + resultObj.resultContent.identityFrontPic;
                    //     document.getElementById("BackPic").src = "data:image/jpeg;base64," + resultObj.resultContent.identityBackPic;
                    // }

                    that.runCallback(that,resultObj,that.param.error_info);
                    that.runSuccessCallback(that,that.param.error_info)
                } else if (resultObj.resultFlag == "-1") {
                    if (resultObj.errorMsg == "端口打开失败") {
                        that.param.error_info  = "端口打开失败" ;
                        that.runErrorCallback(that,resultObj);
                        Toastr.error("精伦读卡器未连接");
                    } else {
                        that.param.error_info  = resultObj.errorMsg ;
                        that.runErrorCallback(that,resultObj);

                    }
                } else if (resultObj.resultFlag == "-2") {
                    //alert(resultObj.errorMsg);
                    that.param.error_info  = resultObj.errorMsg ;
                    that.runErrorCallback(that,resultObj);
                }
            }
            else if (resultObj.name == "getStatus")
            {
                if (resultObj.resultFlag == "0")
                {
                    if (resultObj.status == "0")
                    {
                    }
                    else
                    {
                        that.param.error_info  = "设备连接已断开，请检查读卡器连接" ;
                        that.runErrorCallback(that,resultObj);
                        Toastr.error("精伦设备连接已断开，请检查读卡器连接");
                    }
                }
            }
            else if (resultObj.name == "readM1Card" || resultObj.name == "writeM1Card" || resultObj.name == "handleAPDUCMD") {
                that.param.ACardResult  = event.data;
            }

        };

        //连接关闭的回调方法
            that.param.websocket.onclose = function () {
            that.param.error_info  = "设备连接已断开，请检查读卡器连接" ;
            that.runErrorCallback(that,resultObj);
            Toastr.error("精伦设备连接已断开，请检查读卡器连接");
            that.disconnect();
            that.param.websocket = null;
        };
            return this.param.websocket;
    },
    connect :function()
    {  //连接设备
        var jsonObj = {
            "name":"connect"
        };

        var jStr = JSON.stringify(jsonObj);

        this.param.websocket.send(jStr);
    },
     disconnect:function()
    {    //断开设备连接
        var jsonObj = {
            "name":"disconnect"
        };

        var jStr = JSON.stringify(jsonObj);

        this.param.websocket.send(jStr);
    },
    startPushInfosWithImg:function()
    {
        //开启推送（带图片)
        var jsonObj = {
            "name":"openPush",
            "withImg": true
        };

        var jStr = JSON.stringify(jsonObj);

        this.param.websocket.send(jStr);
    },
     startPushInfosWithOutImg:function()
    {

        //开启推送（不带图片)
        var jsonObj = {
            "name":"openPush",
            "withImg": false,
        };

        var jStr = JSON.stringify(jsonObj);

        this.param.websocket.send(jStr);
    },
        // 允许重复读卡
     enableRepeatRead:function() {
        var jsonObj = {
            "name":"repeatRead",
            "isRepeatRead": true
        };

        var jStr = JSON.stringify(jsonObj);

         this.param.websocket.send(jStr);
    },

        run: function (){
            let self = this;
            //连接websocket
            this.openWebSocket(function (that){
                //打开设备
                self.connect();
                //开启推送监听
                self.startPushInfosWithImg(); //带图片
                // self.startPushInfosWithOutImg(); //不带图片
                //允许重复读卡
                self.enableRepeatRead();
            });

        },
        stop:function (){
            //断开websocket
            this.param.websocket.close();
            this.param.websocket = null;
        },
    }



    // let CardServiceFactory = {
    //     data:{
    //         current_type:requirejs.s.contexts._.config.config.site.cardreader_type, //需获取读卡器品类类型 （通过后端接口获取）
    //         switch:requirejs.s.contexts._.config.config.site.cardreader_switch,   //需获取读卡器开关配置 （通过后端接口获取）
    //         current:null,
    //     },
    //     getService(server_name,singleton){
    //         if(!this.check())return null;
    //         if(!server_name) server_name = this.data.current_type;
    //         switch (server_name)
    //         {
    //             case "kt8003": //卡尔读卡器
    //                 this.data.current = CAERcardService;
    //                 break;
    //             case "idr210": //精伦读卡器
    //                 this.data.current = jinglunCardService;
    //                 break;
    //             default:
    //                 return null;
    //         }
    //         if(singleton) return this.data.current;
    //         return this.deepClone(this.data.current);
    //     },
    //     check(){
    //         //如果未开启读卡器直接返回null
    //         if(this.data.switch != '1'){
    //             Toastr.error("未开启读卡服务，请在【系统配置】中开启！");
    //             return false;
    //         }
    //         return true;
    //     },
    //      deepClone:function(obj) {
    //     //判断拷贝的要进行深拷贝的是数组还是对象，是数组的话进行数组拷贝，对象的话进行对象拷贝
    //     let objClone = Array.isArray(obj) ? [] : {};
    //     //进行深拷贝的不能为空，并且是对象或者是
    //     if (obj && typeof obj === "object") {
    //         for (key in obj) {
    //             if (obj.hasOwnProperty(key)) {
    //                 if (obj[key] && typeof obj[key] === "object") {
    //                     objClone[key] = deepClone1(obj[key]);
    //                 } else {
    //                     objClone[key] = obj[key];
    //                 }
    //             }
    //         }
    //     }
    //     return objClone;
    // }
    // }


    // window.CAERcardService = CAERcardService;
    // window.CardServiceFactory = CardServiceFactory;